package com.imooc.security;

import java.io.IOException;

import org.apache.commons.codec.binary.Base64;
import org.junit.Test;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/**
 * 单向加密：使用Base64加密及解密的几种方法
 * @author Administrator
 *
 */
public class ImoocBase64 {
	private String srcStr = "imooc security base64";
	private String encipherStr = "aW1vb2Mgc2VjdXJpdHkgYmFzZTY0";
	
	/**
	 * 使用jdk(dt.jar版本,在jre/lib下)自带的算法
	 * 编码和解码的效率并不太好，而且在以后的Java版本可能就不被支援了，不建议使用。
	 */
	@Test
	public void jdkBase64(){
		BASE64Encoder encoder = new BASE64Encoder();
		String encode = encoder.encode(srcStr.getBytes());
		System.out.println("encode:"+encode);
		
		BASE64Decoder decoder = new BASE64Decoder();
		String decodeStr;
		try {
			decodeStr = new String(decoder.decodeBuffer(encipherStr));
			System.out.println("decode:"+decodeStr);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	/**
	 * 最佳方法：
	 * 使用jdk自带的算法,JAVA version:1.8
	 */
	@Test
	public void jdkNewBase64(){
		String encode = java.util.Base64.getEncoder().encodeToString(srcStr.getBytes());
		System.out.println("encode:"+encode);
		
		byte[] decodeBytes = java.util.Base64.getDecoder().decode(encipherStr.getBytes());
		String decode = new String(decodeBytes);
		System.out.println("decode:"+decode);
	}
	
	/**
	 * 第三方jar包：commons-codec-1.10.jar，Apache
	 */
	@Test
	public void commonsCodesBase64(){
		byte[] encodeBytes = Base64.encodeBase64(srcStr.getBytes());
		String encode = new String(encodeBytes);
		System.out.println("encode:"+encode);
		
		byte[] decodeBytes = Base64.decodeBase64(encipherStr.getBytes());
		String decode = new String(decodeBytes);
		System.out.println("decode:"+decode);
	}
	/**
	 * 第三方jar包：bcprov-jdk15on-149.jar，Bouncy Castle
	 */
	@Test
	public void bouncyCastleBase64(){
		byte[] encodeBytes = org.bouncycastle.util.encoders.Base64.decode(srcStr);
		String encode = new String(encodeBytes);
		System.out.println("encode:"+encode);
		
		byte[] decodeBytes = org.bouncycastle.util.encoders.Base64.decode(encipherStr.getBytes()); 
		String decode = new String(decodeBytes);
		System.out.println("decode:"+decode);
	}
	
	
}
